import React, { createContext, useContext, useState, useEffect } from 'react';
import type { ReactNode } from 'react';
import type { User, AuthContextType } from '../types/auth';
import { loginUser, registerUser, changeUserPassword, getCurrentUser } from '../utils/api';

const AuthContext = createContext<AuthContextType | undefined>(undefined);

export const useAuth = () => {
  const context = useContext(AuthContext);
  if (context === undefined) {
    throw new Error('useAuth must be used within an AuthProvider');
  }
  return context;
};

interface AuthProviderProps {
  children: ReactNode;
}

export const AuthProvider: React.FC<AuthProviderProps> = ({ children }) => {
  const [user, setUser] = useState<User | null>(null);
  const [token, setToken] = useState<string | null>(null);
  const [isLoading, setIsLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);

  // 初始化时检查本地存储的token
  useEffect(() => {
    const initAuth = async () => {
      const storedToken = localStorage.getItem('auth_token');
      if (storedToken) {
        try {
          const userData = await getCurrentUser(storedToken);
          setUser(userData);
          setToken(storedToken);
        } catch (error) {
          // Token可能已过期，清除本地存储
          localStorage.removeItem('auth_token');
          console.error('Token验证失败:', error);
        }
      }
      setIsLoading(false);
    };

    initAuth();
  }, []);

  const login = async (identifier: string, password: string) => {
    try {
      setIsLoading(true);
      setError(null);
      
      const response = await loginUser({ identifier, password });
      
      setUser(response.user);
      setToken(response.jwt);
      localStorage.setItem('auth_token', response.jwt);
    } catch (error: any) {
      const errorMessage = error?.error?.message || '登录失败，请检查用户名和密码';
      setError(errorMessage);
      throw error;
    } finally {
      setIsLoading(false);
    }
  };

  const register = async (username: string, email: string, password: string) => {
    try {
      setIsLoading(true);
      setError(null);
      
      const response = await registerUser({ username, email, password });
      
      setUser(response.user);
      setToken(response.jwt);
      localStorage.setItem('auth_token', response.jwt);
    } catch (error: any) {
      const errorMessage = error?.error?.message || '注册失败，请检查输入信息';
      setError(errorMessage);
      throw error;
    } finally {
      setIsLoading(false);
    }
  };

  const logout = () => {
    setUser(null);
    setToken(null);
    setError(null);
    localStorage.removeItem('auth_token');
  };

  const changePassword = async (
    currentPassword: string,
    newPassword: string,
    confirmPassword: string
  ) => {
    if (!token) {
      throw new Error('用户未登录');
    }

    if (newPassword !== confirmPassword) {
      throw new Error('新密码和确认密码不匹配');
    }

    try {
      setIsLoading(true);
      setError(null);
      
      const updatedUser = await changeUserPassword(
        {
          currentPassword,
          password: newPassword,
          passwordConfirmation: confirmPassword,
        },
        token
      );
      
      setUser(updatedUser);
    } catch (error: any) {
      const errorMessage = error?.error?.message || '密码修改失败';
      setError(errorMessage);
      throw error;
    } finally {
      setIsLoading(false);
    }
  };

  const clearError = () => {
    setError(null);
  };

  const value: AuthContextType = {
    user,
    token,
    isLoading,
    error,
    isAuthenticated: !!user && !!token,
    login,
    register,
    logout,
    changePassword,
    clearError,
  };

  return <AuthContext.Provider value={value}>{children}</AuthContext.Provider>;
};